package com.hzhh123.sample.crypto;

import com.hzhh123.crypto.annotation.CryptoType;
import com.hzhh123.crypto.config.CryptoProperties;
import com.hzhh123.crypto.exception.EncryptException;
import com.hzhh123.crypto.handle.AbstractCrypto;
import com.hzhh123.crypto.utils.CryptoPropertiesUtils;
import com.hzhh123.crypto.utils.RC2Utils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author hzhh123
 * @version 1.0
 * @date 2022/4/15 21:40
 * @des
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component
@CryptoType("RC2")
public class RC2CryptoHandle extends AbstractCrypto {
    private final CryptoProperties cryptoProperties;
    @Override
    public String encrypt(String str) {
        CryptoProperties.PairKey cryptoPropertiesPairKey = getCryptoPropertiesPairKey();
        return RC2Utils.encrypt(str,cryptoPropertiesPairKey.getKey());
    }

    @Override
    public String decrypt(String str) {
        CryptoProperties.PairKey cryptoPropertiesPairKey = getCryptoPropertiesPairKey();
        return RC2Utils.decrypt(str,cryptoPropertiesPairKey.getKey());
    }

    private CryptoProperties.PairKey getCryptoPropertiesPairKey() {
        CryptoProperties.PairKey cryptoPropertiesPairKey = CryptoPropertiesUtils.getCryptoPropertiesPairKey("RC2", cryptoProperties);
        if (cryptoPropertiesPairKey == null) {
            throw new EncryptException("RC2加密KEY不能为空");
        }
        if (cryptoPropertiesPairKey.getKey() == null) {
            throw new EncryptException("RC2加密KEY不能为空");
        }
        return cryptoPropertiesPairKey;
    }
}
